<?php

if ($auction_product) {
        $auction_query = tep_db_query("select auctions_starting_price, expires_date, overbid_amount from " . TABLE_AUCTIONS_PRODUCTS . " where products_id = '" . $product_info['products_id']. "' and status = '1' ");
        $auction_infor = tep_db_fetch_array($auction_query);
        //$datetime_count_down = strtotime($auction_infor['expires_date'])-time();
        $datetime_count_down = tep_date_count_down($auction_infor['expires_date']);
        $thours = AUCTION_END_TIMEOFFSET;

$ovbid = substr($currencies->display_price($auction_infor['overbid_amount'], tep_get_tax_rate($product_info['products_tax_class_id'])), 1);

$ddprice = $auction_curr;
$finprce = $ddprice + $ovbid;
}
?>
<script language="javascript"><!--
function check_agree(TheForm) {
  if (TheForm.agree.checked) {
    return true;
  } else {
    alert(unescape('<?php echo CONDITION_AGREEMENT_ERROR; ?>'));
    return false;
  }
}
//--></script>

<script type="text/javascript">
// Dans Auction contrib - modification to form validation - check if bid price is above overbid ammount and above the starting price.

function validate(form) {
// Check to see if terms and conditions is agreed to
if(!document.auction_bid.agree.checked){alert(unescape('<?php echo CONDITION_AGREEMENT_ERROR; ?>'));
return false; }
// Check to see if bbid_price has any data

		// Check to see if bid_price is higher than the current bid
if(document.auction_bid.bid_price.value<<?php 
																										echo $finprce; 
																										
																										?>)
		{
		//as above, a few PHP language definitions here would be good
		alert('Your bid must be at least <?php 
		
		echo $currencies->display_price($finprce,0);
		
		?>');
		
		
		
		return false;
		}

else {
return true;
}
}
// EOF Dans Auction script
</script>
<tr>
  <td>
	<table width="100%" border="1" cellpadding="4" cellspacing="0" bordercolor="#FFFFFF">
	  <tr>
	    <td width="278">
<?php
  $thours = AUCTION_END_TIMEOFFSET;

  if ($auction_product) { 
    $auction_query = tep_db_query("select auctions_starting_price, expires_date, overbid_amount from " . TABLE_AUCTIONS_PRODUCTS . " where products_id = '" . $product_info['products_id']. "' and status = '1' ");
    $auction_infor = tep_db_fetch_array($auction_query);
	$datetime_count_down = strtotime($auction_infor['expires_date'])-time();
	$datetime_count_down = strtotime($auction_infor['expires_date']) - strtotime("NOW");

if($datetime_count_down <= 0) {

$winner = tep_db_query("select MAX(ab.bid_price) as bid_price , ab.customers_id,ap.auctions_id, ap.products_id, pp.products_name, pr.products_model, cc.customers_firstname, cc.customers_lastname, cc.customers_email_address from ".TABLE_AUCTIONS_BIDS." ab,".TABLE_AUCTIONS_PRODUCTS." ap, ".TABLE_CUSTOMERS." cc, ".TABLE_PRODUCTS_DESCRIPTION." pp, ".TABLE_PRODUCTS." pr where ab.auctions_id=ap.auctions_id and ab.customers_id = cc.customers_id and ap.products_id = pp.products_id and ap.products_id = ".$product_info['products_id']." and ap.status = 1 and pr.products_id = ". $product_info['products_id'] . " and ap.expires_date <'". date("Y-m-d").' '. date("G:i:s")."' and ap.notified = 1 GROUP BY auctions_id");

if (tep_db_num_rows($winner) > 0) {

$winner_info = tep_db_fetch_array($winner);
$Auction_id = $winner_info['auctions_id'];

$asbidprice = $winner_info['bid_price'];
$custida = $winner_info['customers_id'];
$asprodid = $product_info['products_id'];
$custname = $winner_info['customers_firstname'] . ' ' . $winner_info['customers_lastname'];
$custmail = $winner_info['customers_email'];
$prodname = $winner_info['products_name'] . ' [' . $winner_info['products_model'] . ']';
$asprodname = $winner_info['products_name'];



tep_db_query("Update " . TABLE_PRODUCTS . " set `products_status` = " . AUCTION_END_PRODUCT ." where `products_id` = '$asprodid'");

tep_db_query("update ".TABLE_AUCTIONS_PRODUCTS." SET status = " . AUCTION_END_OPTIONS . ", date_status_change='" . DATE("Y-m-d H:i:s", strtotime("NOW")) . "' where auctions_id = ".$Auction_id);
tep_db_query("update ".TABLE_AUCTIONS_BIDS." SET bid_status = 'won' where bid_price = ".$asbidprice);
//Add to customers basket
tep_db_query("INSERT INTO ".TABLE_CUSTOMERS_BASKET." (auction_product, customers_id, products_id, customers_basket_quantity,final_price, customers_basket_date_added) VALUES ('1',".$custida.", ".$asprodid.",'1', ".$asbidprice.", ".date("Y-m-d").")");


//ok now we need to mail the customer::::
$msg_subject = EMAIL_NOTIFY_WIN_SUBJECT . $asprodname;
$msg_body = str_replace('[customers_name]', $custname, EMAIL_NOFIFY_WIN_BODY);
$msg_body = str_replace('[product]', $prodname, $msg_body);
$msg_body = str_replace('[auction_id]', $Auction_id, $msg_body);
$msg_body = str_replace('[price]', $asbidprice, $msg_body);

tep_mail($custname, $custmail, $msg_subject, $msg_body, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS);


tep_mail(STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, $msg_subject, $msg_body, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS);

//and update status
tep_db_query("update ".TABLE_AUCTIONS_PRODUCTS." SET notified = '0' where auctions_id = ".$Auction_id);


}

//
}


?>
	      <table width="100%">
	        <tr>
			  <td width="50%" class="main"><?php echo '<b>' . TEXT_AUCTION_PRICE . '</b>&nbsp;' . $products_price; ?></td>
	        </tr>
	        <tr>
			  <td class="main"><?php echo '<b>' . TEXT_EXPIRED_DATE . '</b>&nbsp;' . $auction_infor['expires_date']; ?><br />(<b><span id="countdown_date" >&nbsp;</span></b>&nbsp;<?php echo TEXT_DATETIME_LEFT; ?>)</td>
			</tr>
	        <tr>
			  <td class="main"><?php echo '<b>' . TEXT_OVERBID_AMOUNT . '</b>&nbsp;' . $currencies->display_price($auction_infor['overbid_amount'], tep_get_tax_rate($product_info['products_tax_class_id'])); ?></td>
	        </tr>							
	      </table>
<?php
  } //end if 
	else {
      echo $products_price; 
  } // else if
?>
	    </td>
	    <td width="50%">
<?php // If auction has expired
$mfo_auction_query = mysql_fetch_object(tep_db_query("select auctions_starting_price, expires_date, overbid_amount from " . TABLE_AUCTIONS_PRODUCTS . " where products_id = '" . $product_info['products_id']. "' and status = '1' "));
	if (strtotime($mfo_auction_query->expires_date)<time()) {
		echo tep_end_auction_valid();
	} elseif ( $auction_product ) { // Not sure, but probably similar to - If auction has not expired	
	  	echo tep_draw_form('auction_bid',tep_href_link(FILENAME_PRODUCT_INFO),'post', 'onsubmit="return validate(this);"');
?>
	    <input type="hidden" name="placebid" value="true" id="placebid" />
	    <input type="hidden" name="auction_id" id="auction_id" value="<?php echo $auction_id; ?>" />
	    <input type="hidden" name="products_id" value="<?php echo (int)$HTTP_GET_VARS['products_id']; ?>" id="products_id" />
	      <table>
	        <tr>
	          <td class="main" colspan="2"><?php echo TEXT_BID_PRICE . '&nbsp;' . tep_draw_input_field('bid_price', $bid_price);?></td>
			</tr>
			<tr>
              <td class="main"><a href="javascript:void(0);" onclick="window.open('<?php echo tep_href_link('auction_terms.php' , 'popup=popup'); ?>','auction_terms','400','300','yes');return false"><?php echo CONDITIONS; ?>:</a></td>
		      <td onclick="window.document.auction_bid.agree.checked = !window.document.auction_bid.agree.checked;" align="right" width="20px"><?php echo tep_draw_checkbox_field('agree','true', false, 'onclick="window.document.auction_bid.agree.checked = !window.document.auction_bid.agree.checked;"'); ?></td>
	        </tr>
	        <tr>
	          <td colspan="2"><?php echo tep_image_submit('placebid.gif', IMAGE_BUTTON_PLACEBID); ?></td>
	        </tr>
	    </table></form>
		</td>
<?php
	}
?>	  		
        </td>
	  </tr>
	</table>
  </td>
</tr>
<tr>
  <td class="main"><b><?php echo TEXT_AUCTIONS_BID_LIST; ?></b></td>
</tr>
<tr>
  <td>
    <table border="0" width="100%" cellspacing="0" cellpadding="0">
      <tr>
        <td valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="2" >
          <tr class="productListing-heading" >
            <td class="productListing-heading"><?php echo TABLE_HEADING_NUMBER; ?></td>
            <td class="productListing-heading"><?php echo TABLE_HEADING_CUSTOMERS; ?></td>
            <td class="productListing-heading" align="center"><?php echo TABLE_HEADING_BID_PRICE; ?>&nbsp;</td>
			<td class="productListing-heading"><?php echo TABLE_HEADING_BID_DATE_ADDED; ?></td>
			<td class="productListing-heading" align="center">&nbsp;</td>
          </tr>
<?php
  if (isset($HTTP_GET_VARS['page']) && ($HTTP_GET_VARS['page'] > 1)) $rows = $HTTP_GET_VARS['page'] * MAX_DISPLAY_SEARCH_RESULTS - MAX_DISPLAY_SEARCH_RESULTS;
  $products_query_raw = "select concat(c.customers_firstname, c.customers_lastname) as customers_name, c.customers_id, ab.bid_price, ab.bid_status, ab.bid_date_added from ".TABLE_CUSTOMERS." c, ".TABLE_AUCTIONS_BIDS.' ab,'.TABLE_AUCTIONS_PRODUCTS.' ap where c.customers_id = ab.customers_id and ab.auctions_id=ap.auctions_id and ab.auctions_id='.$auction_id.' order by bid_price DESC ';


  $rows = 0;
  $products_query = tep_db_query($products_query_raw);
  while ($products = tep_db_fetch_array($products_query)) {
    $rows++;

    if (strlen($rows) < 2) {
      $rows = '0' . $rows;
    }
?>
              <tr class="productListing-data" >
                <td class="productListing-data"><?php echo $rows; ?>.</td>
                <td class="productListing-data"><?php echo $products['customers_name']; ?></td>
                <td class="productListing-data" align="center"><?php echo $currencies->display_price($products['bid_price'], tep_get_tax_rate($products['products_tax_class_id']) ); ?>&nbsp;</td>
				<td class="productListing-data"><?php echo $products['bid_date_added']; ?></td>
				<td><?php if ($products['bid_status']=='won') { echo tep_image(DIR_WS_ICONS.'auctionwon.gif',IMAGE_BUTTON_AUCTION_WON); }?>
</td>
              </tr>
<?php
  }
?>
            </table></td>
          </tr>
        </table></td>
      </tr>
<script type="text/javascript">
  function init() {displayTZCountDown(<?=$datetime_count_down?>,lab);}

    // load the original script
    var tz = 0;         //  Offset for your timezone in hours from UTC
    var lab = 'countdown_date';    //  The id of the page entry where the timezone countdown is to show

    ////////// DO NOT EDIT PAST THIS LINE //////////////////

    function displayTZCountDown(countdown,tzcd)  {
    if (countdown < 0) document.getElementById(tzcd).innerHTML = "Sorry, you are too late."; 
      else {
	    var secs = countdown % 60; 
    if (secs < 10) secs = '0'+secs;
      var countdown1 = (countdown - secs) / 60;
      var mins = countdown1 % 60; 
    if (mins < 10) mins = '0'+mins;
      countdown1 = (countdown1 - mins) / 60;
      var hours = countdown1 % 24;
      var days = (countdown1 - hours) / 24;
      document.getElementById(tzcd).innerHTML = days + " <?php echo COUNTDOWN_DAYS; ?> "+hours+ '<?php echo COUNTDOWN_HOURS; ?>'+'  : ' +mins+ '<?php echo COUNTDOWN_MINS; ?> : '+secs+'<?php echo COUNTDOWN_SECS;?>';
      setTimeout('displayTZCountDown('+(countdown-1)+',\''+tzcd+'\');',999);
      }
    }

   window.onload = init;
</script>